package com.example.demo05.config;

import com.example.demo05.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;


/*
isCredentialsNonExpired() 密码是否过期
isAccountNonLocked() 账户是否被锁定 业务意义：是否被冻结
isEnable() 账户是否可用 业务意义：是否被删除

 */
@Component
@Slf4j
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private UserServiceImpl userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登陆用户名,{}",username);
        com.example.demo05.pojo.User user = userService.getByLoginId(username);
        log.info("user:{}",user);
        if(user == null || "".equals(username)){
            throw new UsernameNotFoundException("用户名未找到");
        }
        //密码加密后都是不一样的，因为有一个随机生成的盐值
        String password = user.getPassword();
        //String password = passwordEncoder.encode(dbpassword);


        log.info("数据库密码,{}",password);
        //根据用户名查找用户信息
        //根据查找到的用户信息是否被冻结

        //用户是否过期这些可以写在实现类实现方法里面。
        return new User(username, password, true,true,true,user.getAcountnonlocked(),AuthorityUtils.commaSeparatedStringToAuthorityList(user.getIdentity()));
    }
}
